import {
    createRouter,
    createWebHistory
} from "vue-router";
import { userStore } from '@/store/user'

const routes = [{
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    children: [{
        path: '/',
        name: 'Index',
        component: () => import('@/views/Index.vue'),
    }, {
        path: '/user',
        name: 'User',
        component: () => import('@/views/user/Info.vue'),
    }, {
        path: '/article',
        name: 'Article',
        component: () => import('@/views/community/List.vue'),
    }, {
        path: "/article/publish",
        name: 'Article_add',
        component: () => import('@/views/community/Add.vue'),
    }, {
        path: "/article/:id",
        name: 'Community_detail',
        component: () => import('@/views/community/Detail.vue'),
    }, {
        path: '/shopping',
        name: 'Shopping',
        component: () => import('@/views/shopping/Index.vue'),
    }, {
        path: '/shopping/add',
        name: 'ShoppingAdd',
        component: () => import('@/views/shopping/Add.vue'),
    }, {
        path: '/shopping/:id',
        name: 'ShoppingList',
        component: () => import('@/views/shopping/List.vue'),
    }, {
        path: "/shopping/commodity/:id",
        name: 'shopping_detail',
        component: () => import('@/views/shopping/Detail.vue'),
    }, {
        path: '/user/address',
        name: 'Address',
        component: () => import('@/views/user/Address.vue'),
    }, {
        path: "/user/cart",
        name: 'Cart',
        component: () => import('@/views/shopping/Cart.vue'),
    }, {
        path: "/settle",
        name: 'Settle',
        component: () => import('@/views/shopping/Settle.vue')
    }, {
        path: "/user/order",
        name: 'Order',
        component: () => import('@/views/user/Order.vue')
    }, {
        path: "/order/success",
        name: 'OrderSuccess',
        component: () => import('@/views/user/OrderSuccess.vue')
    }]
}, {
    path: '/home',
    redirect: '/'
}, {
    path: '/user/register',
    name: 'Register',
    component: () => import('@/views/user/Register.vue'),
}, {
    path: '/user/login',
    name: 'Login',
    component: () => import('@/views/user/Login.vue'),
},]

export const router = createRouter({
    history: createWebHistory(),
    routes: routes
})

router.beforeEach((to, from, next) => {
    const user_store = userStore()
    // to表示将要访问的路径
    // from表示从那个页面跳转而来
    // next表示允许跳转到指定位置
    if (to.path === '/user/login' || to.path === '/user/register') return next()
    // 获取用户本地的token, 如果token不存在则跳转到登录页
    if (!user_store.token) return next('/user/login')
    next()
}) 